package com.acsm.commons.sms;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import cn.brilliantfuture.commentry.util.SMSProfile;


/**
 * 
 * Title: Commons ACSM
 * 
 * Author: LiTian
 * 
 * Date: 2016-02-25
 * 
 * Description: 阿里大鱼短信发送
 * 
 */
public class AlidayuSMS extends Thread{
	private static Logger logger = Logger.getLogger(AlidayuSMS.class);
	private String phones;
	private String templateCode;
	private String signName;
	private String params;
	private SMSCallback smsCallback ;
	private String content;
	private String message;
	private String key;
	private Object[] objs;
	
	private SMSProfile smsProfile = SMSProfile.getInstance();
	
	
	private static final String PHONE_REGEX = "^1[34578][0-9]{9}$";
	
	/**
	 * @param phones 手机号码(手机号码以,相隔，最多同时可发200个手机号码)
	 * @param templateCode 短信模版编号
	 * @param signName 短信签名
	 * @param params 短信参数(json数据格式)
	 */
	public AlidayuSMS(String phones, String templateCode, String signName, String params) {
		this.phones = phones;
		this.templateCode = templateCode;
		this.signName = signName;
		this.params = params;
	}
	
	/**
	 * @param phones 手机号码(手机号码以,相隔，最多同时可发200个手机号码)
	 * @param templateCode 短信模版编号
	 * @param signName 短信签名
	 * @param params 短信参数(json数据格式)
	 * @param callback 短信发送回调
	 */
	public AlidayuSMS(String phones, String templateCode, String signName, String params, SMSCallback smsCallback) {
		this.phones = phones;
		this.templateCode = templateCode;
		this.signName = signName;
		this.params = params;
		this.smsCallback = smsCallback;
	}
	

	
	/**
	 * @param phones 手机号码(手机号码以,相隔，最多同时可发200个手机号码)
	 * @param templateCode 短信模版编号
	 * @param signName 短信签名
	 * @param params 短信参数(json数据格式)
	 * @param key 本地数据库短信内容key
	 * @param objs[]  短信内容参数(object数组格式)
	 * @param callback 短信发送回调
	 */
	public AlidayuSMS(String phones, String templateCode, String signName,String params,String key, Object objs[], SMSCallback smsCallback) {
		this.phones = phones;
		this.templateCode = templateCode;
		this.signName = signName;
		this.params = params;
		this.key = key;
		this.objs = objs;
		this.smsCallback = smsCallback;
	}
	
	
	/**
	 * @param phones 手机号码(手机号码以,相隔，最多同时可发200个手机号码)
	 * @param templateCode 短信模版编号
	 * @param signName 短信签名
	 * @param params 短信参数(json数据格式)
	 * @param contents 短信完整内容
	 * @param callback 短信发送回调
	 */
	public AlidayuSMS(String phones, String templateCode, String signName,String params,String contents, SMSCallback smsCallback) {
		this.phones = phones;
		this.templateCode = templateCode;
		this.signName = signName;
		this.params = params;
		this.message=contents;
		this.smsCallback = smsCallback;
	}
	
	@Override
	public void run() {
		logger.info("phones -> " + phones + " templateCode -> " + templateCode + " signName -> " + signName + " params -> " + params);
		
		if (null != key && null != objs){
			message = smsProfile.get(key);
			if (null != message || !"".equals(message)){
				message = MessageFormat.format(message, objs);
			}
		}
		
		String[] strs = phones.split(",");
		
		if (strs.length > 200) {
			logger.error("手机号码数量大于上限200!");
			if (null != smsCallback) {
				smsCallback.callback(phones,"{'code':'-2','msg':'手机号码数量大于上限200!','success':false}",message);
			}
			return;
		}
		
		Pattern pattern = Pattern.compile(PHONE_REGEX);
		for (int i = 0; i < strs.length; i++) {
			Matcher matcher = pattern.matcher(strs[i]);
			if (!matcher.matches()) {
				logger.error(strs[i] + "手机号码格式错误!");
				if (null != smsCallback) {
					smsCallback.callback(phones,"{'code':'-2','msg': " + strs[i] + "'手机号码格式错误!','success':false}",message);
				}
				return;
			}
		}
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {
			HttpUriRequest httpGet = RequestBuilder.get("https://ca.aliyuncs.com/gw/alidayu/sendSms")
					.addHeader("X-Ca-Key", "23303112")
					.addHeader("X-Ca-Secret", "0f8f55698b537684467328fee190cfb3")
					.addParameter("rec_num", phones)
					.addParameter("sms_template_code", templateCode)
					.addParameter("sms_free_sign_name",	signName)
					.addParameter("sms_type", "normal")
					.addParameter("sms_param", params)
					.build();
			
			ResponseHandler<String>	responseHandler	= new ResponseHandler<String>()	{
				public	String handleResponse(HttpResponse response) throws IOException {
					//int status = response.getStatusLine().getStatusCode();
					//System.out.println(status);
					HttpEntity entity = response.getEntity();
					return entity != null ? EntityUtils.toString(entity) : null;
				}
			};
			
			String responseBody	= httpClient.execute(httpGet, responseHandler);
			logger.info("Phones -> " + phones);
			logger.info("Sms send result -> " + responseBody);
			if (null != smsCallback) {
				smsCallback.callback(phones,responseBody,message);
			}
		} catch (Exception e) {
			logger.error("Sms send error!", e);
			if (null != smsCallback) {
				smsCallback.callback(phones,"{'code':'-1','msg':'短息发送异常!','success':false}",message);
			}
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				logger.error("Http client close error!", e);
			}
		}
	}
}
